package com.tk.exam.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.tk.exam.utils.GetRequestJsonUtils;
import com.tk.exam.utils.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


@Component
@Aspect
@Slf4j
public class PageHelperAop {

    private static final ThreadLocal<PageInfo> pageBeanContext = new ThreadLocal<>();

    //以WithPage结尾的Controller方法都是需要分页的方法
    @Before(value = "execution(* com.tk.exam.web..*.*WithPage(..))")
    public void controllerAop(JoinPoint joinPoint) throws Exception {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        PageInfo pageBean = new PageInfo();
        String currentPage = request.getParameter("currentPage");
        String pageSize = request.getParameter("pageSize");
        if (StringUtils.isEmpty(currentPage) || StringUtils.isEmpty(pageSize)) {
            try {
                JSONObject param = GetRequestJsonUtils.getRequestJsonObject(request);
                currentPage = param.getString("currentPage");
                pageSize = param.getString("pageSize");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        pageBean.setCurrentPage(currentPage == null ? 1 : Integer.parseInt(currentPage));
        pageBean.setPageSize(pageSize == null ? 10 : Integer.parseInt(pageSize));

        //将分页参数放置线程变量中
        pageBeanContext.set(pageBean);

    }

    //以WithPage结尾的Dao方法都是需要分页的方法
    @Before(value = "execution(* com.tk.exam.dao..*.*WithPage(..))")
    public void daoAop(JoinPoint joinPoint) throws Exception {
        PageInfo pageBean = pageBeanContext.get();
        PageHelper.startPage(pageBean.getCurrentPage(), pageBean.getPageSize());

        pageBeanContext.remove();
    }

}
